<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SupervisorCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'supervisor:config {--user=www}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'supervisor配置文件生成 [--user=www]';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $str = '';
        foreach ($this->configMap() as $command => $numprocs) {
            $example = $this->supervisorExample();
            $help    = [];
            exec(sprintf('php artisan help %s', $command), $help);
            if ($help[1] ?? '') {
                $example = str_replace('{comment}', $help[1], $example);
            }
            $program = str_replace([' ', ':'], '-', $command);
            $example = str_replace('{program}', $program, $example);
            $example = str_replace('{command}', 'php artisan ' . $command, $example);
            $example = str_replace('{directory}', base_path(), $example);
            $example = str_replace('{stdout_logfile}', storage_path('logs') . '/supervisor.log', $example);
            $example = str_replace('{numprocs}', $numprocs, $example);
            $example = str_replace('{user}', $this->option('user'), $example);
            $str .= $example . "\r\n\r\n";
        }
        $filename = storage_path('app') . '/supervisor-mini.ini';
        file_put_contents($filename, $str);
        echo sprintf("supervisor配置文件生成成功，目录：%s 请复制到对应目录中使用 eg：/etc/supervisor\r\n", $filename);
    }

    /**
     * 命令
     */
    private function configMap(): array
    {
        return [
            'queue:work'                              => 1,
        ];
    }

    /**
     * 模板
     */
    private function supervisorExample(): string
    {
        $config = [
            'command'         => '{command}',
            'directory'       => '{directory}',
            'stdout_logfile'  => '{stdout_logfile}',
            'process_name'    => '%(program_name)s_%(process_num)02d',
            'numprocs'        => '{numprocs}',
            'user'            => '{user}',
            'startsecs'       => '10',
            'autostart'       => 'true',
            'autorestart'     => 'true',
            'redirect_stderr' => 'true',
        ];
        $context = "; {comment}\r\n";
        $context .= "[program:mini-{program}]\r\n";
        foreach ($config as $k => $c) {
            $block = str_repeat(' ', 20 - strlen($k));
            $context .= $k . $block . '=' . $c . "\r\n";
        }

        return $context;
    }
}
